<template>
  <ContentContainer
    :show-pagination="false"
    :show-footer="false"
    :refresh="false"
    inner>
    <a-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      layout="vertical">
      <section v-if="!checkIsWild">
        <div class="text-1 text-sm/22px font-bold">清理全站</div>
        <a-button type="primary" class="w-fit mt-6" @click="handleClear(1)"
          >一键清理</a-button
        >
        <a-divider :size="2" style="border-bottom-style: dotted" />
      </section>
      <div class="text-1 text-sm/22px font-bold mb-6">自定义</div>
      <a-form-item field="multi_urls" hide-label>
        <basic-textarea
          v-model:value="formData.multi_urls"
          word-limit-type="multiple-line"
          :maxLength="1000"
          placeholder="URL 一行一个，支持带通配符，例如：
https://www.example.com/*.mp4
https://www.example.com/index*
http://www.example.com/index.html"
          :width="800"
          :height="240"
          :autoSize="true"></basic-textarea>
      </a-form-item>
      <!--
      <a-form-item hide-label asterisk-position="end">
        <section class="flex flex-col">
          <a-checkbox v-model="isEncode" class="w-fit">
            <span class="text-sm/22px">URL Encode</span>
          </a-checkbox>
          <span class="text-5 text-xs/5"
            >若 URL 含有中文，请开启 URL Encode 开关，对中文编码转换。</span
          >
        </section>
      </a-form-item>
      -->
      <section>
        <a-button type="primary" :loading="saveLoading" @click="handleClear(2)"
          >提交</a-button
        >
      </section>
    </a-form>
  </ContentContainer>
</template>
<script lang="ts" setup>
import { postApiSitePurgeApi } from '@/apis/modules/site/site'
import { type FieldRule, type FormInstance } from '@arco-design/web-vue'
import { siteDomainKey } from '@/constants/inject'
import { omit } from 'lodash-es'
import { ResultEnum } from '@/apis/http'
import { useAppStore } from '@/stores/app'
const appStore = useAppStore()
const route = useRoute()
const id = computed(() => route.params.id as string)
const siteDomain = inject(siteDomainKey)

const formRef = ref<FormInstance>()
const formData = ref({
  urls: [],
  purge_type: 1,
  multi_urls: '',
  id: id.value
})
//检查当前域名是否为泛域名
const checkIsWild = computed(() => siteDomain?.value.includes('*'))

// const isEncode = ref(false)
const formRules = computed<{ [key: string]: FieldRule[] }>(() => {
  return {
    purge_type: [
      {
        required: true,
        message: '请选择'
      }
    ],
    multi_urls: [
      { required: true, message: '请输入内容', trigger: 'blur' },
      {
        validator(_value, callback) {
          if (urls.value.length > 1000) {
            callback('超过最大限制条数')
          }
          callback(
            validateHandler(urls.value, (data) => {
              if (!data.includes('http://') && !data.includes('https://')) {
                callback('URL 必须包含 http:// 或 https://')
              }
              const error = `URL格式错误`
              return regExpValidateHandler(
                data,
                regexpMap.protocolUrlWithFileType,
                error
              )
            })
          )
        }
      }
    ]
  }
})
const urls = computed(() => {
  return formData.value.multi_urls.split('\n').filter((item) => item.length)
})
const saveLoading = ref(false)
const handleClear = async (type: 1 | 2) => {
  if (type === 1) {
    CloudModal.confirm(
      {
        content: '该操作会清理全站缓存，确认继续？'
      },
      async () => {
        await postApiSitePurgeApi({
          ...omit(formData.value, 'multi_urls', 'urls'),
          purge_type: 1
        } as any).then((res: any) => {
          if (res.code === ResultEnum.SUCCESS) {
            CloudModal.confirm({
              title: '提示',
              content: '任务提交成功，缓存内容将于数分钟后失效',
              okText: '知道了',
              hideCancel: true
            })
          } else if (res.code === ResultEnum.UNAUTHORIZED) {
            appStore.clearLoginInfoAction()
          } else {
            ToastUtils.error(res.message)
          }
        })
      }
    )
  } else {
    const error = await formRef.value?.validate()
    if (error) return false
    const data = {
      ...omit(formData.value, 'multi_urls'),
      purge_type: 2
    }
    //URL Encode
    // if (isEncode.value) {
    // data.urls = formData.value.multi_urls
    //   .split('\n')
    //   .map((item) => encodeURI(item))
    //   .filter(Boolean)
    // } else {
    data.urls = formData.value.multi_urls
      .split('\n')
      .map((item) => decodeURI(item))
      .filter(Boolean)
    // }
    saveLoading.value = true
    await postApiSitePurgeApi({ ...data })
      .then((res: any) => {
        if (res.code === ResultEnum.SUCCESS) {
          CloudModal.confirm({
            title: '提示',
            content: '任务提交成功，缓存内容将于数分钟后失效',
            okText: '知道了',
            hideCancel: true
          })
        } else if (res.code === ResultEnum.UNAUTHORIZED) {
          appStore.clearLoginInfoAction()
        } else {
          ToastUtils.error(res.message)
        }
      })
      .finally(() => {
        saveLoading.value = false
      })
  }
}
</script>

<style lang="less" scoped></style>
